from datetime import timedelta
from django.utils import timezone
from django.http import JsonResponse
from django.views import View
import random
from app.models import User
from utils.RandomNumber import *
from utils.SendCode import *


class SendCodeView(View):
    def post(self, request):
        try:
            id = request.POST.get('id', '暂无数据')  # 获取id
            phone = request.POST.get('phone', '暂无数据')  # 获取phone
            if id == '暂无数据' or phone == '暂无数据':
                return JsonResponse({'code': '400', 'msg': '请填写正确的数据'})
            code = randomNumber()  # 创建随机6位数
            phone_data = User.objects.filter(phone=phone)  # 查找对象
            if len(phone_data) > 0:
                if phone_data[0].id != id:
                    return JsonResponse({'code': '400', 'msg': '手机号已经绑定其他账号'})
                else:
                    return JsonResponse({'code': '400', 'msg': '您当前已经绑定该手机号'})

            id_data = User.objects.get(id=id)  # 查找对象
            sendCode(phone,code)
            id_data.code = code  # 设置验证码存入数据库
            current_datetime = timezone.now()  # 创建当前时间
            one_minute_later = timedelta(minutes=5)  # 计算一分钟后的时间
            future_time = current_datetime + one_minute_later
            id_data.countdown = future_time  # 直接保存带时区信息的datetime对象
            id_data.save()  # 保存数据
            return JsonResponse({'code': '200', 'msg': '验证码已发送'})
        except Exception as e:
            return JsonResponse({"code": "500", "msg": f"服务器错误: {str(e)}"}, status=500)

